/**
 * Window that contains multiple Tabs with one active.
 *
 * @author Andrey Anisimov <hercules@inbox.ru>
 * @see core.ui.TabWindow
 */

import core.ui.Window;
import core.ui.Menu;
import core.ui.MenuItem;
import core.util.Listeners;

class TabBar extends Menu {
	
	this.TabBar = function(parent, x, y, width, height) {
		super(parent, x, y, width, height);
		this.listeners = new Listeners(['onTabSelected']);
	}

	this.addTabListener = function(listener) {
		this.listeners.add(listener);
	}

	this.removeTabListener = function(listener) {
		this.listeners.remove(listener);
	}

	/**
	 * Adds new item to the tab control.
	 * 
	 * @param text (string) tab text.
	 * @return Window
	 */
	this.addItem = function(text) {
		var item = new MenuItem(this);
		item.setStyle('float', 'left');
		item.setStyleName('TabItem');
		item.setText(text);
		item.index = this.getItemCount();
		item.onclick = bind(this, this.onItemClick);
		return super.addItem(item);
	}
	
	/**
	 * Sets the item with specified index selected.
	 *
	 * @param i (int) selected item index.
	 */
	this.selectItem = function(i) {
		var item = this.getItem(i);
		if (!item) return;
		
		// Clear previous selected item style
		var selected = this.getItem(this.selectedIndex);
		if (selected instanceof Window) {
			selected.removeStyleName('TabItem-selected');
		}
		
		// Make new item selected
		item.addStyleName('TabItem-selected');
		this.selectedIndex = i;
	}
	
	/**
	 * Gets the selected item index.
	 *
	 * @return int
	 */
	this.getSelectedItem = function() {
		return this.selectedIndex;
	}

	this.fireTabSelected = function() {
		this.listeners.call('onTabSelected', [this]);
	}

	this.onItemClick = function(event, target, item) {
		if (item.index != this.selectedIndex) {
			this.selectItem(item.index);
			this.fireTabSelected();
			event.cancel();
		}
	}
}